package com.joeyzh.utils;

import android.support.annotation.Nullable;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;

/**
 * Created by Joey on 2018/11/22.
 * @author Joey
 * 取实体类的属性，并赋值
 * 比如
 * class Person{
 *     private String name；
 *     public void setName(String name){
 *         this.name = name;
 *     }
 *     public String getName(){
 *         return name;
 *     }
 *
 * }
 *
 * 就可以通过
 * Person person = new Person();
 * ModelGetSetUtil util = new ModelGetSetUtil(person)
 * // 设置person的 name 属性
 * util.setValue("name","张艺谋");
 * // 获取person的 name 属性
 * util.getValue("name");
 *
 */

public class ModelGetSetUtil<Bean extends Object> {

    private Bean entityBean;

    public ModelGetSetUtil(Bean entityBean) {
        this.entityBean = entityBean;
    }

    public void setValue(String key, String value) {

        Class cls = entityBean.getClass();
        try {
            Method[] m = cls.getMethods();
            for (int i = 0; i < m.length; i++) {
                if (("set" + key).toLowerCase().equals(m[i].getName().toLowerCase())) {
                    m[i].invoke(entityBean, value);
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("TypeParameterUnusedInFormals")
    @Nullable
    public <T extends Object> T getValue(String key) {

        Class cls = entityBean.getClass();
        try {
            Method[] m = cls.getMethods();
            for (int i = 0; i < m.length; i++) {
                if (("get" + key).toLowerCase().equals(m[i].getName().toLowerCase())) {
                    return (T) m[i].invoke(entityBean);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
